<script setup>
import {showToast, showLoadingToast, closeToast} from 'vant';
import {useRefresh} from "@/hooks/useRefresh";
import {useRegionTree} from "@/hooks/useRegionTree.js";
import {
  addHouseVerify,
  getCommunity,
  getHouseVerifyPersonaInfo,
  getHouseVerifyVariousData,
  getLatestHouseVerify, miniLogin
} from "@/api/business.js";
import {STORAGE_TOKEN_KEY} from "@/stores/mutation-type.js";
// 表单
const form = ref({
  name: "",
  phone: "",
  code: "",
  uuid: "",

  region: "",
  street: "",

  communityId: "",
  communityName: "",

  buildingNumber: "",
  unitNumber: '',
  houseNumberInfo: "",
});

//  查询分页
const query = ref({
  page: 1,
  pageSize: 10,
});
// 总共多少页
const total = ref(4);

// 分页器
const changePageNum = (type) => {
  if (type == '-') {
    if (query.value.page <= 1) {
      return
    }
    query.value.page = query.value.page - 1

  } else {
    if (query.value.page >= total.value) {
      return
    }
    query.value.page = query.value.page + 1
  }
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  });
}

// form ref
const refForm = ref(null);

const dialogShow = ref(false)
// 阅读倒计时
const countdown = ref(4);
// 是否勾选已阅读
const confirmed = ref(false)
// 阅读倒计时定时器
const dialogTimer = ref(undefined)
// 弹框关闭
const closeModal = () => {
  addHouseVerify(form.value).then(res => {
    console.log(res);
    if(res.code==200){
      showToast({
        message: "提交成功！",
        duration: 2000,
        forbidClick: true,
      });
      init()
    }else{
      showToast({
        message: res?.msg ?? "提交失败！",
        duration: 2000,
        forbidClick: true,
      });
    }
  }).finally(()=>{
    dialogShow.value = false
  })
}

const dialogClosed = () => {
  confirmed.value = false
  countdown.value = 4
  if (dialogTimer.value) {
    clearInterval(dialogTimer.value);
  }
}

// 表单提交
const onSubmit = (e) => {
  e.preventDefault();




  refForm.value.validate().then(() => {
    dialogShow.value = true
    dialogTimer.value = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(dialogTimer.value);
      }
    }, 1000);
  })
};


const refreshHandler = () => {
  refreshInit()
}

const {loading, onRefresh} = useRefresh(refreshHandler)

// 区域数据
const {regionTree} = useRegionTree()
// 街道数据
const streetTree = ref([])

// 小区
const communityTree = ref([])
// 单元号
const ldTree = Array(10).fill(0).map((_, index) => {
  return {
    text: `${index + 1}栋`,
    value: index + 1,
  }
})

// 单元号
const unitTree = Array(10).fill(0).map((_, index) => {
  return {
    text: `${index + 1}单元`,
    value: index + 1,
  }
})

const regionTreeHandler = (value) => {
  let target = regionTree.value.find(item => {
    return item.value == value
  })

  if (target) {
    streetTree.value = target.childrens
  }
// 小区数据根据区域来
  getCommunity(value).then(res => {
    console.log(res);
    if (res.code == 200) {
      communityTree.value = res.data.map(ele => {
        return {
          text: ele.communityName,
          value: ele.id,
          ...ele
        }
      })
    }
  })
}
//
const houseTreeHandler = (value) => {
  let target = communityTree.value.find(item => {
    return item.id == value
  })
  if (target) {
    form.value.communityName = target.text
  }
}


const initTimer = ref(undefined)

const login=async () =>{
  let loginForm = {
    "username":"13817021542",
    "password":"f7dc681c"
  }

  const route = useRoute()
  console.log(route)
  let username= route.query?.username
  if(username){
    loginForm.username = username
  }

  let res = await miniLogin(loginForm)
  console.log(res,"=============")
  if(res.code== 200){
    let token =  res.data?.miniToken
    if(token){
      localStorage.setItem(STORAGE_TOKEN_KEY, token);
    }
  }
}

onMounted(async () => {

  // todo 登录（测试用，正式不环境不用调用）
  await login()



  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })
  try{
    await init()
  }finally {
    closeToast()
  }

  initTimer.value = setInterval(() => {
    init()
  }, 1000 * 30)

})

onUnmounted(() => {
  if (initTimer.value) {
    clearInterval(initTimer.value);
  }
})


const init = () => {

  return  Promise.allSettled([_getHouseVerifyVariousData(), _getLatestHouseVerify(), _getHouseVerifyPersonaInfo()])

}

const refreshInit = async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })
  try{
    await init()
  }finally {
    closeToast()
  }
}

//  获取统计的
const countInfo = ref({
  registerTotalNum: '-',
  registeredNum: '-',
  toBeRegisteredNum: '-',
  verifyTotalNum: '-',
  verifiedNum: '-',
  toBeVerifiedNum: '-',
})
const _getHouseVerifyVariousData = () => {
  getHouseVerifyVariousData().then(res => {
    if (res.code == 200) {
      countInfo.value = res.data
    }
  })
}


let list = ref([]);

const _getLatestHouseVerify = () => {
  getLatestHouseVerify().then(res => {
    if (res.code == 200) {
      list.value = res.data
      // list.value = []
    }
  })
}

// 是否已提交
const registerInfo = ref({
  registerFlag: false, // 否
  serialNo: '-',
  registerUpperLimitFlag: false, // 否
  verifyRejectReason: false, // 否
  verifyStatus: false, // 否
  verifyUpperLimitFlag: false, // 否
})

const _getHouseVerifyPersonaInfo = () => {
  getHouseVerifyPersonaInfo().then(res => {
    console.log(res);
    if (res.code == 200) {
      registerInfo.value ={
        ...res.data,
      }
    }
  })
}


const classOptions = {
  limitMoveNum: 6,
};




</script>

<template>
<!--    <van-pull-refresh v-model="loading" @refresh="onRefresh">-->
  <div class="h-full overflow-auto  container">
    <div class="header bg-[var(--theme-color)] p-[10px_var(--padding-x)_10px]">
      <div class="header——title flex justify-between items-center">
        <span class="color-[#fff] text-[14px]">房屋回收报名</span>
        <span class="color-[#fff] text-[12px]" @click="refreshHandler">刷新</span>
      </div>
      <div class=" color-[#fff] grid grid-cols-3 gap-10	mt-[10px]">
        <div class="list_item ">
          <span class="list_item_value">{{ countInfo?.registerTotalNum }}</span>
          <span class="list_item_label">总报名名额</span>
        </div>
        <div class="list_item ">
          <span class="list_item_value">{{ countInfo?.registeredNum }}</span>
          <span class="list_item_label">已报名</span>
        </div>
        <div class="list_item ">
          <span class="list_item_value">{{ countInfo?.toBeRegisteredNum }}</span>
          <span class="list_item_label">剩余报名名额</span>
        </div>
        <div class="list_item">
          <span class="list_item_value">{{ countInfo?.verifyTotalNum }}</span>
          <span class="list_item_label">复核总数</span>
        </div>
        <div class="list_item ">
          <span class="list_item_value">{{ countInfo?.toBeVerifiedNum }}</span>
          <span class="list_item_label">待复核</span>
        </div>
        <div class="list_item ">
          <span class="list_item_value">{{ countInfo?.verifiedNum }}</span>
          <span class="list_item_label">已复核数</span>
        </div>
      </div>
    </div>

    <div class="main-form p-[10px_var(--padding-x)_0px]" v-if="!registerInfo.registerFlag">

      <van-form ref="refForm">
        <van-cell-group inset>
          <div
            class="p-x-[var(--van-cell-horizontal-padding)] p-y-[10px] color-[#323233] text-[14px] font-bold border-b border-b-[#f0f0f0]">
            填写报名信息
          </div>
          <van-field
            required
            v-model="form.name"
            name="真实姓名"
            label="真实姓名"
            placeholder="真实姓名"
            autocomplete="off"
            :rules="[{ required: true, message: '请填写真实姓名' }]"
          />
          <van-field
            v-model="form.phone"
            required
            name="手机号码"
            label="手机号码"
            placeholder="手机号码"
            autocomplete="off"
            :rules="[{ required: true, message: '请填写正确的手机号码', pattern: /^1[3-9]\d{9}$/ }]"
          />
          <HlCode
            v-model="form.code"
            required
            name="短信验证码"
            label="短信验证码"
            placeholder="短信验证码"
            autocomplete="off"
            :phone="form.phone"
            @getCode="uuid => form.uuid = uuid "
            :rules="[{ required: true, message: '请填写短信验证码' }]"
          >

          </HlCode>

          <HlSelect
            v-model="form.region"
            required
            name="行政区域"
            label="行政区域"
            placeholder="请选择行政区域"
            autocomplete="off"
            :columns="regionTree"
            @onConfirm="regionTreeHandler"
            :rules="[{ required: true, message: '请选择行政区域' }]"
          ></HlSelect>
          <HlSelect
            v-model="form.street"
            required
            name="街道"
            label="街道"
            placeholder="请选择街道"
            autocomplete="off"
            :columns="streetTree"
            :rules="[{ required: true, message: '请选择街道' }]"
          ></HlSelect>
          <HlSelect
            v-model="form.communityId"
            required
            name="小区"
            label="小区"
            placeholder="请选择小区"
            autocomplete="off"
            :columns="communityTree"
            @onConfirm="houseTreeHandler"
            :rules="[{ required: true, message: '请选择小区' }]"
          ></HlSelect>

          <!--            <HouseSelecter-->
          <!--              v-model="form.house"-->
          <!--              required-->
          <!--              name="小区"-->
          <!--              label="小区"-->
          <!--              placeholder="请选择小区"-->
          <!--              :rules="[{ required: true, message: '请选择小区' }]"-->
          <!--            >-->

          <!--            </HouseSelecter>-->

          <HlSelect
            v-model="form.buildingNumber"
            required
            name="楼栋"
            label="楼栋"
            placeholder="请选择楼栋"
            autocomplete="off"
            :columns="ldTree"
            :rules="[{ required: true, message: '请选择楼栋' }]"
          ></HlSelect>
          <HlSelect
            v-model="form.unitNumber"
            required
            name="单元"
            label="单元"
            placeholder="请选择单元"
            autocomplete="off"
            :columns="unitTree"
            :rules="[{ required: true, message: '请选择单元' }]"
          ></HlSelect>


          <van-field
            v-model="form.houseNumberInfo"
            required
            name="房间号"
            label="房间号"
            placeholder="房间号"
            autocomplete="off"
            :rules="[{ required: true, message: '请填写房间号' }]"
          />
        </van-cell-group>
        <div style="margin-top: 16px;">
          <van-button round block type="primary" native-type="submit" @click.stop="onSubmit">
            提交报名
          </van-button>
        </div>
      </van-form>
    </div>


    <div class="finished_show bg-white p-[20px] color-[#000]" v-else>
      <div class="text-center ">
        <span class="text-[14px]">报名状态：</span><span class="color-[#52c41a]">报名成功！</span>
      </div>
      <div class="text-center text-[14px]">
        当前报名第 <span class="color-[red] text-[18px]">{{ registerInfo.serialNo }}</span> 名。
      </div>

      <div class="text-center">
        <div>
          <span class="text-[14px]">复核状态：</span>
          <span class="color-[#fa8c16] text-[16px]" v-if="registerInfo.verifyStatus==1">待复核！</span>
          <span class="color-[#52c41a] text-[16px]" v-if="registerInfo.verifyStatus==2">复合通过！</span>
          <span class="color-[#d90909] text-[16px]" v-if="registerInfo.verifyStatus==3">复合拒绝！</span>
        </div>
        <div>
          <div v-if="registerInfo.verifyStatus==2">
            <div class="text-center color-[#52c41a] text-[16px]">
              恭喜您！您的报名已通过！
            </div>
          </div>
          <div v-if="registerInfo.verifyStatus==3">
            <div class="text-center ">
              <span class="text-[14px]">拒绝原因</span> ：<span class="color-[#d90909] text-[16px]">
              {{registerInfo.verifyRejectReason ?? '-'}}
            </span>
            </div>
          </div>
        </div>

<!--        <Result></Result>-->
      </div>


      <div class="text-center text-[14px] color-[#d90909]" v-if="registerInfo.verifyUpperLimitFlag">
        复核名额满
      </div>


    </div>


    <div class="finished_list py-[0px]">
      <div class="finished_list--title p-[10px_var(--padding-x)] flex content-between bg-[#f7f8fa]">
        <div  class="">
          <span class="color-[#333] text-[14px] ">最新报名成功</span>
        </div>
        <!--        <div class="ml-auto text-[12px] flex gap-[6px] items-center">-->
        <!--          <span :aria-disabled="query.page<=1" class="color-[#323233] border border-[#ebedf0] p-[2px_6px] rounded-[3px]-->
        <!--[&[aria-disabled='true']]:opacity-50 [&[aria-disabled='true']]:pointer-events-none"-->
        <!--                @click="changePageNum('-')"-->
        <!--          >上一页</span>-->
        <!--          <span class="color-[#333] text-[10px]">{{ query.page }} / {{ total }}</span>-->
        <!--          <span :aria-disabled="query.page>=total" class="color-[#323233] border border-[#ebedf0] p-[2px_6px] rounded-[3px]-->
        <!--[&[aria-disabled='true']]:opacity-50 [&[aria-disabled='true']]:pointer-events-none"-->
        <!--                @click="changePageNum('+')"-->
        <!--          >下一页</span>-->
        <!--        </div>-->
      </div>

      <div class="finished_list--content flex flex-col bg-white px-[var(--padding-x)]">

        <vue3ScrollSeamless
          v-if="list.length"
          class="scroll-wrap"
          :classOptions="classOptions"
          :dataList="list"
        >
          <ul class="ui-wrap">
            <div
              class="finished_list--item flex items-center gap-[10px]  py-[8px] border-b border-b-[#f0f0f0] last:border-b-0"
              v-for="(item,idx) in list" :key="idx">
              <div class="left w-[40px] h-[40px] min-w-0 flex">
                          <span
                            class="bg-[var(--theme-color)] color-[#fff] w-full h-full rounded-[50%] flex justify-center items-center">
                            {{ item.name.slice(0, 1) }}</span>
              </div>
              <div class="right flex flex-1 ">
                <div class="flex flex-col min-w-0">
                  <span class=" text-[13px] color-[#323233]">{{ item.name }}</span>
                  <span class=" text-[11px] color-[#969799]">{{ item.phone }}</span>
                </div>
                <div class="ml-auto ml-[10px] flex items-center content-center">
                  <span v-if="item.status  == 1"
                        class="text-[10px] p-[3px_6px] rounded-[10px] bg-[#fff7e6]  color-[#fa8c16] border border-[#ffd591] ">
                    待复核</span>
                  <span v-if="item.status  == 2"
                        class="text-[10px] p-[3px_6px] rounded-[10px] bg-[#f6ffed]  color-[#52c41a] border border-[#b7eb8f] ">
                    复核通过</span>
                  <span v-if="item.status  == 3"
                        class="text-[10px] p-[3px_6px] rounded-[10px] bg-[#edbaba]  color-[#d90909] border border-[#d51313] ">
                    复核拒绝</span>

                </div>
              </div>
            </div>
          </ul>
        </vue3ScrollSeamless >



        <van-empty v-else description="暂无数据" />
      </div>

    </div>


    <van-dialog v-model:show="dialogShow" title="注意事项" @closed="dialogClosed" :showConfirmButton="false">
      <div class="modal-content p-[8px_16px] color-[#323233]">
        <div class="notice-content text-[13px]">
          <p>1. 请确保填写的信息真实有效，虚假信息将导致报名无效。</p>
          <p>2. 报名成功后，工作人员将在3个工作日内与您联系。</p>
          <p>3. 房屋需符合公司回收标准，具体标准请参考附件说明。</p>
          <p>4. 报名顺序不等于最终审核顺序，以工作人员现场核实为准。</p>
          <p>5. 总报名名额300个，复核名额100个，复核失败将依次顺延。</p>
          <p>6. 如有疑问，请拨打客服热线：400-xxx-xxxx。</p>
        </div>
        <!--        <div class="countdown-number">{{ countdown }}秒</div>-->
        <div class="p-y[8px]">
          <van-checkbox v-model="confirmed" :disabled="countdown > 0" style="margin-bottom: 12px; font-size: 13px; ">
            <!--            <span class="color-[#1989fa]">我已阅读并同意以上注意事项</span>-->
            <span>我已阅读并同意以上注意事项</span>
          </van-checkbox>
        </div>
        <div class="pb-[14px]">
          <van-button
            type="primary"
            size="small"
            block
            @click="closeModal"
            :disabled="!confirmed"
          >
            确认<span v-if="countdown > 0">{{ countdown }}秒</span>
          </van-button>
        </div>
      </div>
    </van-dialog>
  </div>
<!--    </van-pull-refresh>-->
</template>

<style lang="less" scoped>
.container {
  --padding-x: 16px;

  --theme-color: #1989fa;
  --van-primary-color: var(--theme-color);
  --van-button-primary-background: var(--van-primary-color);

  //overflow-y: scroll;

  background: #f7f8fa;

}

.list_item {
  //background: rgba(255, 255, 255, 0.5);
  //border-radius: 3px;
}
</style>
<style lang="less">

.scroll-wrap {
  height: 400px;
  width: 100%;
  margin: 0 auto;
  overflow: hidden;
}


</style>

<route lang="json5">
{
name: 'OriginalHome',
title: '首页',
meta: {
title: 'Home',
},
}
</route>
